﻿using System.ServiceModel;
using System.Windows.Forms;
using CC.Utilities;

namespace CC.Yacht.Server
{
    public partial class FormServer : Form
    {
        public FormServer()
        {
            InitializeComponent();
            Icon = Yacht.Properties.Resources.Die;

            base.Text = Application.ProductName;

            if (!DesignMode)
            {
                LobbyManager.GameCountChanged += LobbyManager_GameCountChanged;
                SessionManager.SessionAdded += SessionManager_SessionAddedOrRemoved;
                SessionManager.SessionRemoved += SessionManager_SessionAddedOrRemoved;

                _YachtServiceHost = new ServiceHost(typeof (YachtService));
                _YachtServiceHost.UnknownMessageReceived += _YachtServiceHost_UnknownMessageReceived;
                _YachtServiceHost.Open();
            }
        }

        #region Private Fields
        private readonly ServiceHost _YachtServiceHost;
        #endregion

        #region Private Event Handlers
        // ReSharper disable InconsistentNaming
        private static void _YachtServiceHost_UnknownMessageReceived(object sender, UnknownMessageReceivedEventArgs e)
        {
            Logging.LogMessage("Unknown Message Received: " + e.Message);
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            SessionManager.Stop();

            if (_YachtServiceHost != null)
            {
                _YachtServiceHost.Close();
            }
        }

        private void LobbyManager_GameCountChanged(object sender, GameCountEventArgs e)
        {
            UpdateToolStripItemText(_ToolStripStatusLabelGames, "Games: " + e.Count);
        }

        private void SessionManager_SessionAddedOrRemoved(object sender, SessionAddedEventArgs e)
        {
            UpdateToolStripItemText(_ToolStripStatusLabelUsers, "Users: " + e.Total);
        }
        // ReSharper restore InconsistentNaming
        #endregion

        #region Private Methods
        private void UpdateToolStripItemText(ToolStripItem toolStripItem, string text)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new MethodInvoker(() => UpdateToolStripItemText(toolStripItem, text)));
            }
            else
            {
                toolStripItem.Text = text;
            }
        }
        #endregion
    }
}
